package com.lcj.hub.common.handler;

import com.lcj.hub.common.Result;
import com.lcj.hub.common.constant.ErrorCode;
import com.lcj.hub.common.exception.DuplicateSubmissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(DuplicateSubmissionException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> handleDuplicateSubmissionException(DuplicateSubmissionException ex) {
        log.error("重复提交异常: {}", ex.getMessage());
        return Result.failed(ErrorCode.DUPLICATE_SUBMISSION, "重复提交: " + ex.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> handleNullPointerException(NullPointerException ex) {
        log.error("空指针异常: {}", ex.getMessage());
        return Result.failed(ErrorCode.NULL_POINTER, "服务器内部错误: " + ex.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> handleIllegalArgumentException(IllegalArgumentException ex) {
        log.error("非法参数异常: {}", ex.getMessage());
        return Result.failed(ErrorCode.ILLEGAL_ARGUMENT, "非法参数: " + ex.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> handleRuntimeException(RuntimeException ex) {
        log.error("运行时异常: {}", ex.getMessage());
        return Result.failed(ErrorCode.RUNTIME, "服务器内部错误: " + ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> handleException(Exception ex) {
        log.error("服务器内部错误: {}", ex.getMessage());
        return Result.failed(ErrorCode.EXCEPTION, "服务器内部错误: " + ex.getMessage());
    }
}
